<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="编号" prop="productTypeCode">
        <el-input
          v-model="queryParams.productTypeCode"
          placeholder="编号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="名称" prop="productTypeName">
        <el-input
          v-model="queryParams.productTypeName"
          placeholder="请输入产品类型名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="产品类型" prop="productType">
        <el-select
          v-model="queryParams.productType"
          placeholder="请选择产品类型"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.CARDBOARD_PRODUCTION_PRODUCT_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
<!--      <el-form-item label="客户 ID" prop="customerId">-->
<!--        <el-input-->
<!--          v-model="queryParams.customerId"-->
<!--          placeholder="请输入客户 ID"-->
<!--          clearable-->
<!--          @keyup.enter="handleQuery"-->
<!--          class="!w-240px"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['erp:base-box-type:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['erp:base-box-type:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
      v-loading="loading"
      :data="list"
      :stripe="true"
      :show-overflow-tooltip="true"
      highlight-current-row
      @current-change="handleCurrentChange"
    >
<!--      <el-table-column label="主键 ID" align="center" prop="id" />-->
      <el-table-column label="产品类型编号" align="center" prop="productTypeCode" />
      <el-table-column label="产品类型名称" align="center" prop="productTypeName" />
      <el-table-column label="产品类型" align="center" prop="productType">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.CARDBOARD_PRODUCTION_PRODUCT_TYPE" :value="scope.row.productType" />
        </template>
      </el-table-column>
<!--      <el-table-column label="客户" align="center" prop="customerId" />-->
      <el-table-column label="客户" align="center" :formatter="formatCustomerName" />
      <el-table-column label="单价(英寸)" align="center" prop="unitPriceInch" />
      <el-table-column label="面积（英寸）" align="center" prop="areaInch" />
      <el-table-column label="立方（英寸）" align="center" prop="volumeInch" />
      <el-table-column label="重量（英寸）" align="center" prop="weightInch" />
      <el-table-column label="单价（厘米）" align="center" prop="unitPriceCm" />
      <el-table-column label="面积（厘米）" align="center" prop="areaCm" />
      <el-table-column label="体积（厘米）" align="center" prop="volumeCm" />
      <el-table-column label="重量（厘米）" align="center" prop="weightCm" />
      <el-table-column label="包装数" align="center" prop="packageQuantity" />
      <el-table-column label="规格拼接方式" align="center" prop="specConcatMode" />
      <el-table-column label="规格分隔字符" align="center" prop="specSeparator" />
      <el-table-column label="规格单位字符" align="center" prop="specUnit" />
      <el-table-column label="用料默认单位" align="center" prop="defaultMaterialUnit" />
      <el-table-column label="最大纸长" align="center" prop="maxPaperLength" />
      <el-table-column label="用料报价单位" align="center" prop="materialPriceUnit" />
      <el-table-column label="送货金额" align="center" prop="deliveryPrice" />
      <el-table-column label="送货总重量" align="center" prop="deliveryTotalWeight" />
      <el-table-column label="总重量取舍" align="center" prop="totalWeightRounding">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.ERP_DECIMAL_ROUNDING_MODE" :value="scope.row.totalWeightRounding" />
        </template>
      </el-table-column>
      <el-table-column label="取舎位数" align="center" prop="roundingDigits">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.DECIMAL_ROUND_TYPE" :value="scope.row.roundingDigits" />
        </template>
      </el-table-column>
      <el-table-column label="是否默认" align="center" prop="isDefault">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.INFRA_BOOLEAN_STRING" :value="scope.row.isDefault" />
        </template>
      </el-table-column>
      <el-table-column label="默认加损耗" align="center" prop="defaultWithLoss">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.INFRA_BOOLEAN_STRING" :value="scope.row.defaultWithLoss" />
        </template>
      </el-table-column>
      <el-table-column label="BOM是否重新计价" align="center" prop="bomRecalculate">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.INFRA_BOOLEAN_STRING" :value="scope.row.bomRecalculate" />
        </template>
      </el-table-column>
      <el-table-column label="不进行加价设置" align="center" prop="noExtraCharge">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.INFRA_BOOLEAN_STRING" :value="scope.row.noExtraCharge" />
        </template>
      </el-table-column>
      <el-table-column label="按用料计算成本单价" align="center" prop="costPriceByMaterial">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.INFRA_BOOLEAN_STRING" :value="scope.row.costPriceByMaterial" />
        </template>
      </el-table-column>
      <el-table-column label="工艺数量按成品推算" align="center" prop="processQtyByProduct">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.INFRA_BOOLEAN_STRING" :value="scope.row.processQtyByProduct" />
        </template>
      </el-table-column>
      <el-table-column label="默认不上传文件" align="center" prop="noUploadFileByDefault">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.INFRA_BOOLEAN_STRING" :value="scope.row.noUploadFileByDefault" />
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" align="center" min-width="120px">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['erp:base-box-type:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['erp:base-box-type:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <BaseBoxTypeForm ref="formRef" @success="getList" />
  <!-- 子表的列表 -->
  <ContentWrap>
    <el-tabs model-value="baseBoxMaterialFormula">
      <el-tab-pane label="用料公式" name="baseBoxMaterialFormula">
        <BaseBoxMaterialFormulaList :box-type-id="currentRow.id" />
      </el-tab-pane>
      <el-tab-pane label="生产工序" name="baseBoxProductionProcess">
        <BaseBoxProductionProcessList :box-type-id="currentRow.id" />
      </el-tab-pane>
      <el-tab-pane label="计算参数公式" name="boxCalculationFormula">
        <BoxCalculationFormulaList :box-type-id="currentRow.id" />
      </el-tab-pane>
      <el-tab-pane label="图像坐标" name="boxImageCoordinate">
        <BoxImageCoordinateList :box-type-id="currentRow.id" />
      </el-tab-pane>
      <el-tab-pane label="参数公式" name="baseBoxParameterFormula">
        <BaseBoxParameterFormulaList :box-type-id="currentRow.id" />
      </el-tab-pane>
      <el-tab-pane label="备注" name="baseBoxRemark">
        <BaseBoxRemarkList :box-type-id="currentRow.id" />
      </el-tab-pane>
    </el-tabs>
  </ContentWrap>
</template>

<script setup lang="ts">
import { getStrDictOptions, DICT_TYPE } from '@/utils/dict'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { BaseBoxTypeApi, BaseBoxTypeVO } from '@/api/erp/baseboxtype'
import BaseBoxTypeForm from './BaseBoxTypeForm.vue'
import BoxCalculationFormulaList from './components/BoxCalculationFormulaList.vue'
import BoxImageCoordinateList from './components/BoxImageCoordinateList.vue'
import BaseBoxMaterialFormulaList from './components/BaseBoxMaterialFormulaList.vue'
import BaseBoxParameterFormulaList from './components/BaseBoxParameterFormulaList.vue'
import BaseBoxProductionProcessList from './components/BaseBoxProductionProcessList.vue'
import BaseBoxRemarkList from './components/BaseBoxRemarkList.vue'
import {BaseBoxInnerOuterConfigApi} from "@/api/erp/baseboxinnerouterconfig";

/** ERP基础资料-箱型资料 列表 */
defineOptions({ name: 'BaseBoxType' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<BaseBoxTypeVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  productTypeCode: undefined,
  productTypeName: undefined,
  productType: undefined,
  customerId: undefined,
  createTime: []
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await BaseBoxTypeApi.getBaseBoxTypePage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await BaseBoxTypeApi.deleteBaseBoxType(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await BaseBoxTypeApi.exportBaseBoxType(queryParams)
    download.excel(data, 'ERP基础资料-箱型资料.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 选中行操作 */
const currentRow = ref({}) // 选中行
const handleCurrentChange = (row) => {
  currentRow.value = row
}

// ** 客户 & 材质列表 ** 
const customerList = ref<{ id: string; name: string }[]>([])

/** 获取客户列表 */
const getAllBaseCustomer = async () => {
  try {
    const response = await BaseBoxInnerOuterConfigApi.getAllBaseCustomer();
    if (response) {
      customerList.value = response;
    }
  } catch (error) {
    console.error("获取客户列表失败:", error);
  }
}

// 格式化客户名称
const formatCustomerName = (row) => {
  const customer = customerList.value.find(c => c.id === row.customerId)
  return customer ? customer.name : null
}

onMounted(() => {
  Promise.all([
    getList(),
    getAllBaseCustomer()
  ])
})
</script>
